package com.gitee.wsl.compose.ext.ui


import androidx.core.bundle.Bundle
import androidx.lifecycle.Lifecycle
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavController
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.json.Json
import kotlinx.serialization.serializer

/**
 * Sets a result for the previous backstack entry.
 *
 * The result type has to be KotlinX Serializable.
 */
 inline fun <reified R : Any> NavController.setResult(
    data: R,
) {
    setResultImpl(data, serializer())
}

@OptIn(ExperimentalSerializationApi::class)
@PublishedApi
internal fun <R : Any> NavController.setResultImpl(
    data: R,
    resultSerializer: KSerializer<R>,
) {
    val result = Json.encodeToString(resultSerializer, data)
    val resultKey = resultSerializer.descriptor.serialName + "_result"
    previousBackStackEntry?.savedStateHandle?.set(resultKey, result)
}

/**
 * @SuppressLint("UnrememberedGetBackStackEntry")
 * @Composable
 * internal fun Home(
 * 	navController: NavController,
 * ) {
 * 	var bottomSheetResult by rememberSaveable { mutableIntStateOf(-1) }
 * 	NavigationResultEffect<Destinations.BottomSheet.Result>(
 * 		backStackEntry = remember(navController) { navController.getBackStackEntry<Destinations.Home>() },
 * 		navController = navController,
 * 	) { result ->
 * 		bottomSheetResult = result.id
 * 	}
 * 	Home(
 * 		navigate = navController::navigate,
 * 		bottomSheetResult = bottomSheetResult,
 * 	)
 * }
 *
 * @Composable
 * private fun Home(
 * 	navigate: (Any) -> Unit,
 * 	bottomSheetResult: Int,
 * ) {
 * 	Column {
 * 		Text("Home")
 *
 * 		OutlinedButton(onClick = { navigate(Destinations.Modal1) }) {
 * 			Text("Modal 1")
 * 		}
 *
 * 		OutlinedButton(onClick = { navigate(Destinations.BottomSheet) }) {
 * 			Text("BottomSheet")
 * 		}
 *
 * 		Text("BottomSheetResult: $bottomSheetResult")
 * 	}
 * }
 *
 *
 */

fun NavBackStackEntry.lifecycleIsResumed() =
    this.lifecycle.currentState == Lifecycle.State.RESUMED

fun NavController.popBackStackWithLifecycle() {
    if (currentBackStackEntry?.lifecycleIsResumed() == true) {
        popBackStack()
    }
}

/**
 * Returns the arguments stored in [this] back stack entry.
 *
 * @throws IllegalStateException If no arguments were supplied during navigation.
 */
fun NavBackStackEntry.requireArguments(): Bundle {
    return checkNotNull(arguments) { "NavBackStackEntry $this does not have any arguments." }
}


